﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace YawetagLib.Data
{
    public static class DataContextBuilder
    {
        public static void RegisterFactory(Type factoryType)
        {
            if (!IsFactoryRegistered)
            {
                FactoryType = factoryType;
            }
        }

        public static void UnRegisterFactory()
        {
            FactoryType = null;
        }

        public static void RegisterDataContexts(params DataContextInfo[] dataContextInfos)
        {
            RegisterFactory(typeof(DefaultDataContextFactory));

            DataContextInfos = dataContextInfos.ToList();
        }

        public static IDataContextFactory GetFactory()
        {
            if (IsFactoryRegistered)
            {
                IDataContextFactory factory = (IDataContextFactory)Activator.CreateInstance(FactoryType);
                CheckForRegisteredDataContexts(factory as BaseDataContextFactory);

                return factory;
            }

            throw new DataException("Expected DataContext registrations, use DataContextBuilder.RegisterFactory or DataContextBuilder.RegisterDataContexts");
        }

        private static void CheckForRegisteredDataContexts(BaseDataContextFactory factory)
        {
            if (factory != null)
            {
                foreach (DataContextInfo dataContextInfo in DataContextInfos)
                {
                    factory.Register(dataContextInfo);
                }
            }
        }

        public static bool IsFactoryRegistered
        {
            get { return FactoryType != null; }
        }

        private static Type FactoryType { get; set; }

        private static IList<DataContextInfo> DataContextInfos { get; set; }
    }
}
